package com.chaychan.library;

import ohos.agp.components.*;
import ohos.app.Context;

import java.util.ArrayList;
import java.util.List;

public class BottomBarLayout extends DirectionalLayout implements PageSlider.PageChangedListener, Component.LayoutRefreshedListener {

    protected PageSlider mViewPager;
    private List<BottomBarItem> mItemViews = new ArrayList<>();
    private int mCurrentItem;//当前条目的索引
    private boolean mSmoothScroll;


    public BottomBarLayout(Context context) {
        this(context, null);
    }

    public BottomBarLayout(Context context, AttrSet attrSet) {
        this(context, attrSet, "");
    }

    public BottomBarLayout(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        mSmoothScroll = AttrUtils.getBooleanFromAttr(attrSet, "smoothScroll", false);

        setLayoutRefreshedListener(this);

        setBindStateChangedListener(new BindStateChangedListener() {
            @Override
            public void onComponentBoundToWindow(Component component) {

            }

            @Override
            public void onComponentUnboundFromWindow(Component component) {
                if (mViewPager != null) {
                    try {
                        mViewPager.removePageChangedListener(BottomBarLayout.this);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
        });
    }

    /**
     * 监听组件加载完成
     *
     * @param component
     */
    @Override
    public void onRefreshed(Component component) {
        if (mItemViews == null || mItemViews.size() == 0) {
            init();
        }

    }

    public void setViewPager(PageSlider viewPager) {
        this.mViewPager = viewPager;

        if (mViewPager != null) {
            PageSliderProvider adapter = mViewPager.getProvider();
            if (adapter != null && adapter.getCount() != getChildCount()) {
                throw new IllegalArgumentException("LinearLayout的子View数量必须和ViewPager条目数量一致");
            }
        }

        if (mViewPager != null) {
            mViewPager.addPageChangedListener(this);
        }
    }


    private void init() {
        mItemViews.clear();
        int childCount = getChildCount();
        if (childCount == 0) {
            return;
        }

        for (int i = 0; i < childCount; i++) {
            if (getComponentAt(i) instanceof BottomBarItem) {
                BottomBarItem bottomBarItem = (BottomBarItem) getComponentAt(i);
                mItemViews.add(bottomBarItem);
                //设置点击监听
                bottomBarItem.setClickedListener(new MyOnClickListener(i));
            } else {
                throw new IllegalArgumentException("BottomBarLayout的子View必须是BottomBarItem");
            }
        }

        if (mCurrentItem < mItemViews.size())
            mItemViews.get(mCurrentItem).refreshTab(true);

    }

    public void addItem(BottomBarItem item) {
        DirectionalLayout.LayoutConfig layoutConfig = new DirectionalLayout.LayoutConfig(ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_CONTENT);
        layoutConfig.weight = 1;
        item.setLayoutConfig(layoutConfig);
        addComponent(item);
        init();
    }

    public void removeItem(int position) {
        if (position >= 0 && position < mItemViews.size()) {
            BottomBarItem item = mItemViews.get(position);
            if (mItemViews.contains(item)) {
                resetState();
                removeComponentAt(position);
                init();
            }
        }
    }


    @Override
    public void onPageSliding(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageChosen(int position) {
        resetState();
        mItemViews.get(position).refreshTab(true);
        if (onItemSelectedListener != null) {
            onItemSelectedListener.onItemSelected(getBottomItem(position), mCurrentItem, position);
        }
        mCurrentItem = position;//记录当前位置
    }

    @Override
    public void onPageSlideStateChanged(int state) {

    }

    private class MyOnClickListener implements ClickedListener {

        private int currentIndex;

        public MyOnClickListener(int i) {
            this.currentIndex = i;
        }

        @Override
        public void onClick(Component component) {
            //回调点击的位置
            if (mViewPager != null) {
                //有设置viewPager
                if (currentIndex == mCurrentItem) {
                    //如果还是同个页签，使用setCurrentItem不会回调OnPageSelecte(),所以在此处需要回调点击监听
                    if (onItemSelectedListener != null) {
                        onItemSelectedListener.onItemSelected(getBottomItem(currentIndex), mCurrentItem, currentIndex);
                    }
                } else {
                    mViewPager.setCurrentPage(currentIndex, mSmoothScroll);
                }
            } else {
                //没有设置viewPager
                if (onItemSelectedListener != null) {
                    onItemSelectedListener.onItemSelected(getBottomItem(currentIndex), mCurrentItem, currentIndex);
                }

                updateTabState(currentIndex);
            }
        }

    }


    private void updateTabState(int position) {
        resetState();
        mCurrentItem = position;
        mItemViews.get(mCurrentItem).refreshTab(true);
    }

    /**
     * 重置当前按钮的状态
     */
    private void resetState() {
        if (mCurrentItem < mItemViews.size()) {
            if (mItemViews.get(mCurrentItem).isSelected()) {
                mItemViews.get(mCurrentItem).refreshTab(false);
            }
        }
    }

    public void setCurrentItem(int currentItem) {
        if (mViewPager != null) {
            mViewPager.setCurrentPage(currentItem, mSmoothScroll);
        } else {
            if (onItemSelectedListener != null) {
                onItemSelectedListener.onItemSelected(getBottomItem(currentItem), mCurrentItem, currentItem);
            }
            updateTabState(currentItem);
        }
    }


    /**
     * 设置未读数
     *
     * @param position  底部标签的下标
     * @param unreadNum 未读数
     */
    public void setUnread(int position, int unreadNum) {
        mItemViews.get(position).setUnreadNum(unreadNum);
    }

    /**
     * 设置提示消息
     *
     * @param position 底部标签的下标
     * @param msg      未读数
     */
    public void setMsg(int position, String msg) {
        mItemViews.get(position).setMsg(msg);
    }

    /**
     * 隐藏提示消息
     *
     * @param position 底部标签的下标
     */
    public void hideMsg(int position) {
        mItemViews.get(position).hideMsg();
    }

    /**
     * 显示提示的小红点
     *
     * @param position 底部标签的下标
     */
    public void showNotify(int position) {
        mItemViews.get(position).showNotify();
    }

    /**
     * 隐藏提示的小红点
     *
     * @param position 底部标签的下标
     */
    public void hideNotify(int position) {
        mItemViews.get(position).hideNotify();
    }

    public int getCurrentItem() {
        return mCurrentItem;
    }

    public void setSmoothScroll(boolean smoothScroll) {
        this.mSmoothScroll = smoothScroll;
    }


    public BottomBarItem getBottomItem(int position) {
        return mItemViews.get(position);
    }

    private OnItemSelectedListener onItemSelectedListener;

    public interface OnItemSelectedListener {
        void onItemSelected(BottomBarItem bottomBarItem, int previousPosition, int currentPosition);
    }

    public void setOnItemSelectedListener(OnItemSelectedListener onItemSelectedListener) {
        this.onItemSelectedListener = onItemSelectedListener;
    }


}
